package service

import (
	"database/sql"
	"errors"
	"gin-chat-server/common"
	"gin-chat-server/dto"
	"gin-chat-server/models"

	"gorm.io/gorm"
)

type AuthService struct {
	db *gorm.DB
}

func NewAuthService() *AuthService {
	return &AuthService{
		db: common.GetDB(),
	}
}

type UserLogin struct {
	Id        string         `json:"id"`
	Username  string         `json:"username"`
	Password  string         `json:"password"`
	Email     sql.NullString `json:"email" gorm:""`
	Phone     sql.NullString `json:"phone"`
	Status    int            `json:"status"`
	CreatedAt string         `json:"createdAt"`
}

func (s *AuthService) Login(loginParams dto.JackpotUserLoginDTO) (map[string]interface{}, error) {
	var user models.User
	if err := s.db.Where("username = ?", loginParams.Username).First(&user).Error; err != nil {
		return nil, err
	}
	if user.Password != loginParams.Password {
		return nil, errors.New("密码错误")
	}
	if user.State != 1 {
		return nil, errors.New("账号未激活")
	}
	token, err := common.GenerateToken(user.ID, user.Username)
	if err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"token": token,
	}, nil
}

func (s *AuthService) Register(registerParams dto.JackpotUserLoginDTO) (map[string]interface{}, error) {
	var user models.User
	if err := s.db.Where("username = ?", registerParams.Username).First(&user).Error; err == nil {
		return nil, errors.New("用户名已存在")
	}
	if err := s.db.Where("email = ?", registerParams.Email).First(&user).Error; err == nil {
		return nil, errors.New("邮箱已存在")
	}
	if err := s.db.Where("phone = ?", registerParams.Phone).First(&user).Error; err == nil {
		return nil, errors.New("手机号已存在")
	}
	user = models.User{
		Username: registerParams.Username,
		Password: registerParams.Password,
		Nickname: registerParams.Nickname,
		Email:    registerParams.Email,
		Phone:    registerParams.Phone,
	}
	if err := s.db.Create(&user).Error; err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"id": user.ID,
	}, nil
}
